package com.openspring.business.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.swing.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.openspring.framework.service.AbstractGenericService;
import com.openspring.framework.tree.Node;
import com.openspring.platform.dao.DeptDAO;
import com.openspring.business.dao.EmployeeDAO;
import com.openspring.platform.model.Dept;
import com.openspring.business.model.Employee;
import com.openspring.business.service.EmployeeService;

@Service("employeeService")
public class EmployeeServiceImpl extends AbstractGenericService<Employee, Long> implements EmployeeService {
	
	private EmployeeDAO employeeDAO;
	
	@Resource(name = "employeeDAO")
	public void setEmployeeDAO(EmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
		super.setGenericDAO(employeeDAO);
	}
	
	private DeptDAO deptDAO;
	
	@Resource(name = "deptDAO")
	public void setDeptServie(DeptDAO deptDAO) {
		this.deptDAO = deptDAO;
	}

	@Override
	public Node getEmployeeTree() {
		Node root = new Node();
		root.setText("root");
		Map<Long, Node> omap = new HashMap<Long, Node>();
		Map<Long, List<Node>> umap = new HashMap<Long, List<Node>>();
		List<Dept> depts = deptDAO.queryAll();
		List<Employee> employees = employeeDAO.queryAll();
		Iterator<Dept> oiter = depts.iterator();
		Iterator<Employee> uiter = employees.iterator();
		while(oiter.hasNext()) {
			Node onode = new Node();
			Dept dept = oiter.next();
			BeanUtils.copyProperties(dept, onode);
			onode.setText(dept.getCnName());
			onode.setIconCls("dept");
			omap.put(onode.getId(), onode);
		}
		while(uiter.hasNext()) {
			Node unode = new Node();
			Employee employee = uiter.next();
			BeanUtils.copyProperties(employee, unode);
			unode.setText(employee.getCnName());
			//unode.setChecked(Integer.parseInt(employee.get("checked").toString())==0? false : true);
			unode.setIconCls("employee");
			Long deptId = employee.getDeptId();
			List<Node> list = umap.get(deptId);
			if(list == null) {
				list = new ArrayList<Node>();
				list.add(unode);
			} else {
				list.add(unode);
			}
			umap.put(deptId, list);
		}
		Set<Map.Entry<Long, Node>> entrySet = omap.entrySet();
		Iterator<Map.Entry<Long, Node>> iter = entrySet.iterator();
		while(iter.hasNext()) {
			Node node = iter.next().getValue();
			List<Node> list = umap.get(node.getId());
			if(list != null) {
				node.getChildren().addAll(list);
			}
			if(node.getParentId() == null) {
				root.getChildren().add(node);
			} else {
				omap.get(node.getParentId()).getChildren().add(node);
			}
		}
		root.sort(SortOrder.ASCENDING);
		return root;
	}
}
